package service

import (
	pb "e-commerce/services/order-service/api/pb"
	"e-commerce/services/order-service/internal/mq"
	"e-commerce/services/order-service/internal/repository"
	"encoding/json"
	"log"
)

type OrderService struct {
	Repo *repository.OrderRepository
	Mq   *mq.OrderMQ
}

func NewOrderService(configPath string) *OrderService {
	repo := repository.NewMySQLRepository(configPath)
	mq := mq.NewOrderMQ(configPath)
	return &OrderService{
		Repo: repo,
		Mq:   mq,
	}
}

func (s *OrderService) CreateOrder(order *pb.Order) (int64, error) {
	orderID, err := s.Repo.CreateOrder(order)
	if err != nil {
		return 0, err
	}
	reversedMessage := mq.ReversedMessage{
		OrderID:     orderID,
		ProductID:   order.ProductId,
		ReversedNum: order.Quantity,
	}
	log.Println("reversedMessage", reversedMessage)
	reversedMessageBytes, err := json.Marshal(reversedMessage)
	if err != nil {
		return 0, err
	}
	log.Println("reversedMessageBytes", reversedMessageBytes)
	err = s.Mq.CreatePublish(reversedMessageBytes)
	if err != nil {
		return 0, err
	}
	return orderID, nil
}

func (s *OrderService) GetOrder(orderID int64) (*pb.Order, error) {
	order, err := s.Repo.GetOrder(orderID)
	if err != nil {
		return nil, err
	}
	return order, nil
}

func (s *OrderService) UpdateOrderStatus(orderID int64, status string) error {
	return s.Repo.UpdateOrderStatus(orderID, status)
}

func (s *OrderService) MarkOrderPaid(orderID int64, success bool) error {
	var rollbackMessage mq.StockRollbackMessage
	rollbackMessage.OrderID = orderID
	rollbackMessageBytes, err := json.Marshal(rollbackMessage)
	if err != nil {
		return err
	}
	if !success {
		log.Printf("订单支付失败,发送库存回滚消息")
		s.Mq.FailedRollbackPublish(rollbackMessageBytes)
	}
	log.Printf("订单支付是否成功：%v,更改订单状态", success)
	return s.Repo.MarkOrderPaid(orderID, success)
}

func (s *OrderService) CancelOrder(orderID int64) error {
	status, err := s.Repo.QueryOrderStatus(orderID)
	if err != nil {
		return err
	}
	if status == "reserved" {
		var rollbackMessage mq.StockRollbackMessage
		rollbackMessage.OrderID = orderID
		rollbackMessageBytes, err := json.Marshal(rollbackMessage)
		if err != nil {
			return err
		}
		err = s.Mq.CancelRollbackPublish(rollbackMessageBytes)
		if err != nil {
			log.Printf("发送库存回滚消息失败: %v", err)
			return err
		}
	}
	err = s.Repo.UpdateOrderStatus(orderID, "canceled")
	if err != nil {
		log.Printf("更新订单状态为取消，失败: %v", err)
		return err
	}
	log.Printf("取消订单成功")
	return nil
}
